package com.simtop.hj.service.imp;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.simtop.hj.common.ServerResponse;
import com.simtop.hj.mapper.UserMapper;
import com.simtop.hj.pojo.*;
import com.simtop.hj.service.UserService;
import com.simtop.hj.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    public UserMapper userMapper;

    @Resource
    public RedisUtil redisUtil;

    private Logger logger= LoggerFactory.getLogger(UserServiceImpl.class);

    @Override
    public User login(User user) {
        return userMapper.login(user);
    }

    @Override
    public List<Role> getRole() {
        return userMapper.getRole();
    }

    @Override
    public ServerResponse<String> register(User user) {
        String checkCode = (String) redisUtil.get("hjemail_"+user.getEmail());
        if(StringUtils.isEmpty(checkCode)){
            return ServerResponse.createByErrorMsg("验证码已失效");
        }
        else if(!user.getCheckCode().equals(checkCode)){
            return ServerResponse.createByErrorMsg("验证码错误");
        }else{
            user.setCreateTime(new Date());
            User checkEmail=userMapper.checkEmail(user.getEmail());
            if(ObjectUtils.isEmpty(checkEmail)){
                User checkUsername=userMapper.checkUsername(user);
                if(ObjectUtils.isEmpty(checkUsername)){
                    System.out.println(user);
                    int i = userMapper.register(user);
                    if (i != 0) {
                        return ServerResponse.createBySuccessMsg("注册成功");
                    } else {
                        return ServerResponse.createByErrorMsg("注册失败");
                    }
                }else{
                    return ServerResponse.createByErrorMsg("该用户名已存在");
                }
            }else{
                return ServerResponse.createByErrorMsg("该邮箱已经注册过了!");
            }
        }
    }

    @Override
    public void registerUser(User user) {
        user.setCreateTime(new Date());
        User checkEmail = userMapper.checkEmail(user.getEmail());
        if (ObjectUtils.isEmpty(checkEmail)) {
            User checkUsername = userMapper.checkUsername(user);
            if (ObjectUtils.isEmpty(checkUsername)) {
                userMapper.register(user);
            }
        }
    }

    /**
     * 邮箱验证
     * @param email
     * @return
     */
    @Override
    public ServerResponse<String> generateCheckCode(String email) {
        synchronized (this){
            //邮箱非空验证
            if(email==null||"".equals(email)){
                return ServerResponse.createByErrorMsg("邮箱不能为空,请填入有效地址");
            }
            //生成随机的6位数字验证码
            String verificationCode= SmsRandomCodeUtil.generateRandomSixNum();
            //调用邮箱发送
            AliyunMailUtil.sendMail(email,"上海对外经贸大学虚拟仿真实验项目用户注册","您的验证码为："+verificationCode+"。此验证码三分钟内有效，请及时注册。"+"<br><br>"+"本邮件是系统自动发送的，请勿直接回复！感谢您的注册，祝您使用愉快！");
            redisUtil.set("hjemail_"+email,verificationCode,180);
            // todo 发送的验证码拼接了之前的验证码？？ 获取content内容时候出现getContent现象
            // todo 2019年8月28日09:23:18 接口中屏蔽验证码
            return ServerResponse.createBySuccessMsg("发送验证码成功");
        }
    }

    /**
     * 忘记密码时候，根据邮箱返回验证码
     * @param email
     * @return
     */
    @Override
    public ServerResponse<String> forgetSendEmailCode(String email) {
        //验证邮箱是否存在
        User resultCount = userMapper.checkEmail(email);
        if(ObjectUtils.isEmpty(resultCount)){
            return ServerResponse.createByErrorMsg("邮箱不存在！");
        }
        //生成随机的验证码
        String verificationCode= SmsRandomCodeUtil.generateRandomSixNum();
        //调用邮箱发送
        AliyunMailUtil.sendMail(email,"上海对外经贸大学虚拟仿真实验项目用户重置密码","您的验证码为："+verificationCode+"。此验证码五分钟内有效，请及时重置密码。"+"<br><br>"+"本邮件是系统自动发送的，请勿直接回复！");
        //发送成功保存邮箱地址对应的验证码 todo 5分钟 已解决
        redisUtil.set("hjforget_"+email,verificationCode,300);
        return ServerResponse.createBySuccessMsg("验证码已经发送");
    }

    /**
     * 修改密码
     * @param user
     * @return
     */
    @Override
    public ServerResponse<String> updatePassword(User user) {
        String checkCode = (String) redisUtil.get("hjforget_"+user.getEmail());
        int updatePasswordResult=0;
        if (StringUtils.isEmpty(checkCode)) {
            return ServerResponse.createByErrorMsg("验证码已经失效");
        } else {
            if (!checkCode.equals(user.getCheckCode())) {
                return ServerResponse.createByErrorMsg("验证码输入错误");
            } else {
                User checkEmailUser = userMapper.checkEmail(user.getEmail());
                if (!ObjectUtils.isEmpty(checkEmailUser)) {
                    updatePasswordResult = userMapper.updatePassword(user);
                }
            }
        }
        if (updatePasswordResult != 0) {
            return ServerResponse.createBySuccessMsg("修改成功");
        } else {
            return ServerResponse.createByErrorMsg("修改失败");
        }
    }


    @Override
    public void expertLogin(User expertLoginUser) {
        userMapper.expertLogin(expertLoginUser);
    }

    @Override
    public ServerResponse<PageInfo> searchUser(Integer pageNum, Integer pageSize, String username,String subjects,String loginName,String studyYear) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> userList = userMapper.searchUser(username,subjects,loginName,studyYear);
        PageInfo pageInfo = new PageInfo(userList);
        return ServerResponse.createBySuccess(pageInfo);
    }


    @Override
    public ServerResponse deleteUser(Integer id) {
        int deleteStatus = userMapper.deleteUser(id);
        if (deleteStatus != 0) {
            return ServerResponse.createBySuccessMsg("成功删除该学生");
        } else {
            return ServerResponse.createByErrorMsg("删除该学生失败");
        }
    }

    @Override
    public void deleteVisitorRole() {
        userMapper.deleteVisitorRole();
    }


    @Override
    public Integer getUserNums() {
        return userMapper.getUserNums();
    }

    @Override
    public List<HJPP> getHJPP() {
        return userMapper.getHJPP();
    }


    @Override
    public List<DSHJ> getDSHJ() {
        return userMapper.getDSHJ();
    }

    @Override
    public List<WBHJ> getWBHJ() {
        return userMapper.getWBHJ();
    }

    @Override
    public List<WineWorld> getIndexData() {
        return userMapper.getIndexData();
    }


    @Override
    public void createReportCard(Grade grade) {
        userMapper.createReportCart(grade);
    }


    @Override
    public ServerResponse addComment(Grade grade) {
        Integer addStatus=userMapper.addComment(grade);
        if(addStatus!=0){
            return ServerResponse.createBySuccess("成功添加评论");
        }else{
            return ServerResponse.createByErrorMsg("添加评论失败");
        }
    }

    @Override
    public ServerResponse<PageInfo<Grade>> getGrade(Integer pageSize, Integer pageNum, User user) {
        if (StringUtils.isEmpty(pageNum)) {
            pageNum = 1;
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Grade> gradeList = userMapper.getGrade(user);
        PageInfo pageInfo = new PageInfo(gradeList);
        return ServerResponse.createBySuccess(pageInfo);
    }


    @Override
    public Integer getExperiment() {
        return userMapper.getExperiment();
    }

    @Override
    public Echarts3 selectScoreUser() {
        return userMapper.selectScoreUser();
    }


    @Override
    public void insertRedisCiYun() {
        try{
            logger.info("成功调用词云");
            if(redisUtil.hasKey("wordFrequencyPic")){
                logger.info("天猫数据缓存中已存在");
            }else{
                String dcWordFrequencyPic=userMapper.getCx(1);
                String mcWordFrequencyPic=userMapper.getCx(2);
                String xrcWordFrequencyPic=userMapper.getCx(3);
                List<WordFrequencyData>  wordFrequencyDataList= WordFrequencyAnalyzer.getWordFrequencyAnalyzerAll(Arrays.asList(dcWordFrequencyPic));
                redisUtil.lSet("wordFrequencyPic",wordFrequencyDataList);
                List<WordFrequencyData>  wordFrequencyDataList1= WordFrequencyAnalyzer.getWordFrequencyAnalyzerAll(Arrays.asList(mcWordFrequencyPic.split(",")));
                redisUtil.lSet("wordFrequencyPic",wordFrequencyDataList1);
                List<WordFrequencyData>  wordFrequencyDataList2= WordFrequencyAnalyzer.getWordFrequencyAnalyzerAll(Arrays.asList(xrcWordFrequencyPic));
                redisUtil.lSet("wordFrequencyPic",wordFrequencyDataList2);
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.info("词云调用失败{}",e.getLocalizedMessage());
        }
    }

    @Override
    public ServerResponse updateUser(User user) {
        int i=userMapper.updateUser(user);
        if(i!=0){
            return ServerResponse.createBySuccess("修改成功");
        }else{
            return ServerResponse.createByErrorMsg("修改失败");
        }
    }

    @Override
    public ServerResponse addUser(User user) {
       User user1= userMapper.checkEmail(user.getEmail());
       if(null!=user1){
            return ServerResponse.createByErrorMsg("添加失败,该邮箱已存在！");
       }
        int i=userMapper.addUser(user);
        if(i!=0){
            return ServerResponse.createBySuccess("添加成功");
        }else{
            return ServerResponse.createByErrorMsg("添加失败");
            }
    }

    @Override
    public List<DownGrade> downLoadGrade(User user) {
        List<DownGrade> downGradeList=userMapper.downLoadGrade(user);
        return downGradeList;
    }

    @Override
    public ServerResponse deleteGrade(Integer gradeId) {
        int i=userMapper.deleteGrade(gradeId);
        if(i!=0){
            return ServerResponse.createBySuccess("删除成功");
        }else{
            return ServerResponse.createByErrorMsg("删除失败");
        }
    }

    @Override
    public ServerResponse addScore(Grade grade) {
        int i=userMapper.addScore(grade);
        if(i!=0){
            return ServerResponse.createBySuccess("成功添加成绩");
        }else{
            return ServerResponse.createByErrorMsg("添加成绩失败");
        }
    }
}
